package com.qzxy.premiumhotelsystem.common.aspect;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.qzxy.premiumhotelsystem.common.annotation.LogExecutionTime;
import com.qzxy.premiumhotelsystem.common.enums.LogLevel;
import com.qzxy.premiumhotelsystem.common.result.Result;
import com.qzxy.premiumhotelsystem.domain.entity.Guests;
import com.qzxy.premiumhotelsystem.service.LogsService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

import static com.qzxy.premiumhotelsystem.common.enums.LogLevel.*;


/**
 * @Author: iQNRen
 * @Description: 生成日志切面
 * @Date: 2024/9/18 13:52 周三
 * @Version: 1.0
 */
@Aspect
@Component
public class LoggingAspect {

    @Autowired
    private LogsService logsService;
    @Pointcut("@annotation(com.qzxy.premiumhotelsystem.common.annotation.LogExecutionTime)")
    public void Pointcut() {
        // 切入点签名
    }

    @Around("Pointcut()")
    public void logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        LogExecutionTime annotation = method.getAnnotation(LogExecutionTime.class);
        //  获取方法参数
        //  Object[] args = joinPoint.getArgs();
        //  String username = (String) args[0]; // 假设第一个参数是用户名

        String operator = annotation.operator();
        String message = annotation.message();
        String level = annotation.level().toString();
//        try {
//            operator = StpUtil.getLoginId().toString();
//        }catch (NotLoginException e){
//            throw new RuntimeException("用户未登录，请先登录");
//        }

        logsService.create(operator,message,level);

        // 根据日志级别记录日志
        switch (annotation.level()) {
            case INFO:
                System.out.println("INFO: " + operator + " - " + message);
                break;
            case DEBUG:
                System.out.println("DEBUG: " + operator + " - " + message);
                break;
            case WARN:
                System.out.println("WARN: " + operator + " - " + message);
                break;
            case ERROR:
                System.out.println("ERROR: " + operator + " - " + message);
                break;
        }

    }

    //可获取方法返回参数
    @AfterReturning(pointcut = "Pointcut()", returning = "result")
    public void logMethod(JoinPoint joinPoint, Object result) {

    }
}



